package com.topfun.utils;


import com.google.gson.JsonObject;
import com.topfun.misc.AccessTokenTask;
import com.topfun.vo.AccessToken;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 公众平台通用接口工具类
 */
public class WechatUtil {
    private static      Logger logger           = LoggerFactory.getLogger(WechatUtil.class);
    // 获取access_token的接口地址（GET） 限200（次/天）
    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    // 获取jsapi_ticket的接口地址（GET） 限200（次/天）
    public final static String GET_TICKET       = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

    public static AccessToken accessToken = null; //保存 access_token & jsapi_ticket

    public static AccessTokenTask mTask = null;

    static {
        mTask = new AccessTokenTask();
        mTask.start();
    }
    /**
     * 获取access_token &
     * 获取 jsapi_ticket
     * @return
     */
    public static AccessToken getAccessToken() {

        AccessToken  accessToken = null;
        String       requestUrl  = access_token_url.replace("APPID", Constants.WeChat_App_ID).replace("APPSECRET", Constants.WeChat_App_Secret);
        OkHttpClient client      = new OkHttpClient();
        Request      request     = new Request.Builder().url(requestUrl).get().build();
        try {
            Response   response   = client.newCall(request).execute();
            String     strJson    = response.body().string();
            JsonObject jsonObject = GsonUtil.stringToJsonObject(strJson);
            if (jsonObject.has("errcode")) {
                logger.error(String.format("获取token失败 errcode:{%s} errmsg:{%s}", jsonObject.get("errcode").getAsString(), jsonObject.get("errmsg").getAsString()));
                return null;
            }
            if (null != jsonObject) {
                try {
                    accessToken = new AccessToken();
                    accessToken.setToken(jsonObject.get("access_token").getAsString());
                    accessToken.setExpiresIn(jsonObject.get("expires_in").getAsInt());
                    accessToken.setTicket(getJsApiTicket(accessToken.getToken()));
                    logger.debug(String.format("get token is %s ! ticket is %s !",accessToken.getToken(),accessToken.getTicket()));
                } catch (Exception e) {
                    accessToken = null;
                    // 获取token失败
                }
            }
        } catch (IOException e) {
            logger.error("获取access_token error!");
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 获取jsapi_ticket
     *
     * @return
     */
    public static String getJsApiTicket(String token) {
        String ticket = "";

        String       requestUrl = GET_TICKET.replace("ACCESS_TOKEN", token);
        OkHttpClient client     = new OkHttpClient();
        Request      request    = new Request.Builder().url(requestUrl).get().build();
        try {
            Response   response   = client.newCall(request).execute();
            String     strJson    = response.body().string();
            JsonObject jsonObject = GsonUtil.stringToJsonObject(strJson);
            if (null != jsonObject) {
                try {
                    ticket = jsonObject.get("ticket").getAsString();
                } catch (Exception e) {
                    logger.error(String.format("获取ticket {%s} errcode:{%s} errmsg:{%s} ",jsonObject.get("ticket").getAsString(), jsonObject.get("errcode").getAsString(), jsonObject.get("errmsg").getAsString()),e);
                    // 获取token失败
                }
                logger.info(String.format("获取ticket {%s} errcode:{%s} errmsg:{%s} ",jsonObject.get("ticket").getAsString(), jsonObject.get("errcode").getAsString(), jsonObject.get("errmsg").getAsString()));
            }
        } catch (IOException e) {
            logger.error("获取jsapi_ticket error!");
            e.printStackTrace();
        }
        return ticket;
    }


}
